package com.example.jimanguang.Repositories.untils;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

public class FileUtils {
    //文件上传参数
    public static final String UPLOAD_PARAM_URL="url";
    public static final String UPLOAD_PARAM_MESSAGE="message";
    public static final String UPLOAD_PARAM_STATUS="status";
    public static JSONObject upload(MultipartFile file, String dir) {//文件上传
        JSONObject result = new JSONObject();
        try {
            String originName = file.getOriginalFilename();//获取文件名
            String ext = originName.substring(Objects.requireNonNull(originName).lastIndexOf("."));//获取文件名后缀
            String random = UUID.randomUUID() + ext;//随机名称
            File f = new File(dir + random);
            file.transferTo(f);//上传
            result.put(UPLOAD_PARAM_STATUS, true);
            result.put(UPLOAD_PARAM_MESSAGE, "文件上传成功");
            result.put(UPLOAD_PARAM_URL, dir+random);
        } catch (IOException e) {
            result.put(UPLOAD_PARAM_STATUS, false);
            result.put(UPLOAD_PARAM_MESSAGE, "上传失败:" + e.getMessage());
            result.put(UPLOAD_PARAM_URL, "");
            e.printStackTrace();
        }


        return result;
    }
}